<?php

/**
 * Name: 审核服务层
 * User: Silent
 * Date: 2025-11-07
 * Time: 16:00:00
 */

namespace App\Services\Checkin;

use App\Models\Checkin\LeaderReview;
use App\Models\Checkin\SupervisorReview;
use App\Repositories\Checkin\LeaderReviewRepository;
use App\Repositories\Checkin\SupervisorReviewRepository;
use App\Repositories\Checkin\SignInRecordRepository;
use App\Repositories\Checkin\DutySupervisorRepository;
use App\Services\BaseService;
use App\Services\Checkin\NotificationService;
use Illuminate\Support\Facades\DB;
use Exception;

class ReviewService extends BaseService
{
    protected $leaderReviewRepository;
    protected $supervisorReviewRepository;
    protected $signInRecordRepository;
    protected $dutySupervisorRepository;
    protected $notificationService;

    public function __construct(
        LeaderReviewRepository $leaderReviewRepository,
        SupervisorReviewRepository $supervisorReviewRepository,
        SignInRecordRepository $signInRecordRepository,
        DutySupervisorRepository $dutySupervisorRepository,
        NotificationService $notificationService
    ) {
        $this->leaderReviewRepository = $leaderReviewRepository;
        $this->supervisorReviewRepository = $supervisorReviewRepository;
        $this->signInRecordRepository = $signInRecordRepository;
        $this->dutySupervisorRepository = $dutySupervisorRepository;
        $this->notificationService = $notificationService;
    }

    /**
     * 班长提交审核
     */
    public function submitLeaderReview($leader, $reviewData, $date = null)
    {
        try {
            DB::beginTransaction();

            $date = $date ?: today();

            // 检查是否已经审核过
            if ($this->leaderReviewRepository->hasReviewedToday($leader->id, $leader->team, $date)) {
                throw new Exception('今天已经审核过了，不能重复提交');
            }

            // 创建或更新审核记录
            $review = $this->leaderReviewRepository->createOrUpdateReview(
                $leader->toArray(),
                $reviewData,
                $date
            );

            // // 如果审核状态为异常，通知值班领导
            // if ($review->review_status === LeaderReview::STATUS_REJECTED) {
            //     $this->notificationService->sendAbnormalReviewNotification($review);
            // }

            DB::commit();

            return [
                'success' => true,
                'data' => $review,
                'message' => '审核提交成功'
            ];

        } catch (Exception $e) {
            DB::rollBack();

            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 主管提交审核
     */
    public function submitSupervisorReview($supervisor, $reviewData, $date = null)
    {
        try {
            DB::beginTransaction();

            $date = $date ?: today();

            // 检查是否已经审核过
            if ($this->supervisorReviewRepository->hasReviewedToday($supervisor->id, $date)) {
                throw new Exception('今天已经审核过了，不能重复提交');
            }

            // 创建或更新审核记录
            $review = $this->supervisorReviewRepository->createOrUpdateReview(
                $supervisor->toArray(),
                $reviewData,
                $date
            );

            DB::commit();

            return [
                'success' => true,
                'data' => $review,
                'message' => '审核提交成功'
            ];

        } catch (Exception $e) {
            DB::rollBack();

            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 检查班长当日审核状态
     */
    public function checkLeaderReviewStatus($leader, $date = null)
    {
        try {
            $date = $date ?: today();

            // 查询当日审核记录
            $review = $this->leaderReviewRepository->getLeaderReview(
                $leader->team,
                $date
            );

            // 判断是否已审核
            $hasReviewed = $review && $review->isReviewed();

            return [
                'success' => true,
                'data' => [
                    'has_reviewed' => $hasReviewed
                ]
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 检查主管当日审核状态
     */
    public function checkSupervisorReviewStatus($supervisor, $date = null)
    {
        try {
            $date = $date ?: today();

            // 查询当日审核记录
            $review = $this->supervisorReviewRepository->getSupervisorReview(
                $supervisor->id,
                $date
            );

            // 判断是否已审核
            $hasReviewed = $review && $review->isReviewed();

            return [
                'success' => true,
                'data' => [
                    'has_reviewed' => $hasReviewed
                ]
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取班长待审核数据
     */
    public function getLeaderPendingReview($leader, $date = null)
    {
        try {
            $date = $date ?: today();

            // 获取班组签到记录
            $signRecords = $this->signInRecordRepository->getTeamSignRecords(
                $leader->team,
                $date
            );

            // 检查是否已经审核过
            $existingReview = $this->leaderReviewRepository->getLeaderReview(
                $leader->team,
                $date
            );

            // 获取当天的值班领导信息
            $dutySupervisor = $this->dutySupervisorRepository->getDutySupervisorByDate($date);

            // 按状态分组
            $groupedRecords = $signRecords->groupBy('status');

            return [
                'success' => true,
                'data' => [
                    'date' => $date,
                    'team_name' => $leader->team,
                    'sign_records' => $signRecords,
                    'abnormal_count' => $groupedRecords->get('abnormal', collect())->count(),
                    'normal_count' => $groupedRecords->get('normal', collect())->count(),
                    'total_count' => $signRecords->count(),
                    'existing_review' => $existingReview,
                    'can_review' => !$existingReview || !$existingReview->isReviewed(),
                    'duty_supervisor' => $dutySupervisor,  // 值班领导信息
                    'review_leader' => $leader  // 审核班长信息（当前登录的班长）
                ]
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取主管待审核数据
     */
    public function getSupervisorPendingReview($supervisor, $date = null)
    {
        try {
            $date = $date ?: today();

            // 获取所有班组的签到记录
            $allSignRecords = $this->signInRecordRepository->getAllTeamsSignRecords($date);

            // 获取班长审核记录
            $leaderReviews = $this->leaderReviewRepository->getDailyReviews($date);
            $leaderReviewsMap = $leaderReviews->keyBy('team_name');

            // 获取主管审核记录
            $supervisorReviews = $this->supervisorReviewRepository->getDailyReviews($date);

            $teamsData = [];
            foreach ($allSignRecords as $teamName => $records) {
                $groupedRecords = $records->groupBy('status');
                $leaderReview = $leaderReviewsMap->get($teamName);
                $supervisorReview = $supervisorReviews->get($teamName, collect())->first();

                $teamsData[] = [
                    'team_name' => $teamName,
                    'sign_records' => $records,
                    'abnormal_count' => $groupedRecords->get('abnormal', collect())->count(),
                    'normal_count' => $groupedRecords->get('normal', collect())->count(),
                    'total_count' => $records->count(),
                    'leader_review' => $leaderReview,
                    'supervisor_review' => $supervisorReview,
                    'can_review' => !$supervisorReview || !$supervisorReview->isReviewed()
                ];
            }

            return [
                'success' => true,
                'data' => [
                    'date' => $date,
                    'teams_data' => $teamsData
                ]
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取审核详情
     */
    public function getReviewDetail($teamName, $date, $userRole = 'leader')
    {
        try {
            // 获取班组签到记录
            $signRecords = $this->signInRecordRepository->getTeamSignRecords($teamName, $date);

            // 获取班长审核记录
            $leaderReview = $this->leaderReviewRepository->getLeaderReview($teamName, $date);

            $data = [
                'date' => $date,
                'team_name' => $teamName,
                'sign_records' => $signRecords,
                'leader_review' => $leaderReview
            ];

            // 如果是主管查看，还需要获取主管审核记录
            if ($userRole === 'supervisor') {
                $supervisorReviews = $this->supervisorReviewRepository->getDailyReviews($date);
                $data['supervisor_reviews'] = $supervisorReviews->get($teamName, collect());
            }

            return [
                'success' => true,
                'data' => $data
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取审核记录列表
     */
    public function getReviewRecords($employee, $type = 'leader', $perPage = 15, $filters = [])
    {
        try {
            if ($type === 'leader') {
                $records = $this->leaderReviewRepository->getLeaderReviews(
                    $employee->id,
                    $perPage,
                    $filters
                );
            } else {
                $records = $this->supervisorReviewRepository->getSupervisorReviews(
                    $employee->id,
                    $perPage,
                    $filters
                );
            }

            return [
                'success' => true,
                'data' => $records
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取异常审核统计
     */
    public function getAbnormalReviewStatistics($startDate, $endDate)
    {
        try {
            // 这里可以添加统计逻辑
            // 比如统计某个时间段内的异常审核数量、趋势等

            return [
                'success' => true,
                'data' => [
                    'message' => '统计功能待实现'
                ]
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取主管视图：所有班组状态和组员打卡明细
     */
    public function getSupervisorTeamsView($supervisor, $date = null)
    {
        try {
            $date = $date ?: today()->format('Y-m-d');

            // 获取所有班组的签到记录
            $allSignRecords = $this->signInRecordRepository->getAllTeamsSignRecords($date);

            // 获取所有班长审核记录（包含班长关联信息）
            $leaderReviews = $this->leaderReviewRepository->getDailyReviews($date);
            $leaderReviewsMap = $leaderReviews->keyBy('team_name');

            // 获取当天的值班领导信息
            $dutySupervisor = $this->dutySupervisorRepository->getDutySupervisorByDate($date);

            // 获取当前主管的审核记录
            $supervisorReview = $this->supervisorReviewRepository->getSupervisorReview($supervisor->id, $date);

            $allTeams = [];
            foreach ($allSignRecords as $teamName => $records) {
                $leaderReview = $leaderReviewsMap->get($teamName);

                // 获取班组审核状态和备注
                $reviewStatus = $leaderReview ? $leaderReview->review_status : 'pending';
                $reviewRemark = $leaderReview ? $leaderReview->review_remark : '';

                // 格式化组员明细
                $members = $records->map(function ($record) {
                    return [
                        'id' => $record->id,
                        'name' => $record->employee_name,
                        'status' => $record->status,
                        'signTime' => $record->sign_time->format('H:i'),
                        'bloodPressure' => $record->blood_pressure_systolic . '/' . $record->blood_pressure_diastolic,
                        'temperature' => (string)$record->temperature,
                        'remark' => $record->remark ?: '',
                        // 异常项描述
                        'abnormalDesc' => $record->abnormal_desc,
                    ];
                })->toArray();

                $allTeams[] = [
                    'teamName' => $teamName,
                    'reviewStatus' => $reviewStatus,
                    'reviewRemark' => $reviewRemark,
                    'leaderReview' => $leaderReview,  // 班长审核信息（包含班长关联）
                    'members' => $members
                ];
            }

            return [
                'success' => true,
                'data' => [
                    'date' => $date,
                    'teams' => $allTeams,
                    'total_teams' => count($allTeams),
                    'duty_supervisor' => $dutySupervisor,  // 值班领导信息
                    'supervisor_review' => $supervisorReview  // 主管审核信息
                ]
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
}

